<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>关于JS对象的使用</title>

	<script type="text/javascript">
	//Blog类初始化
	function Blog (body,date) {
		//Blog类的成员变量
		this.body = body;
		this.date = date;

		//Blog类的成员方法
		this.toString = function(){
			return "[" + (this.date.getMonth() + 1) + "/" + this.date.getDate() + "/" + this.date.getFullYear() + "]" + this.body;
		};

		this.toHTML = function(highlight){
			var blogHTML = "";
			blogHTML += highlight ? "<p style='background-color:#EEEEEE'>" : "<p>";
			blogHTML += "<strong>" + (this.date.getMonth() + 1) + "/" + this.date.getDate + "/" + this.date.getFullYear() + "</strong><br/>" + this.body + "</p>";

			return blogHTML;
		};

		this.containsText = function(text){
			return (this.body.toLowerCase().indexOf(text.toLowerCase()) != -1);
		};
	}//Blog类相关东西到这里结束

	//初始化一个Blog对象数组，是一个全局变量
	var blog = [ new Blog("Got the new cube I ordered. It's a real pearl.", new Date("08/14/2008")),
                   new Blog("Solved the new cube but of course, now I'm bored and shopping for a new one.", new Date("08/19/2008")),
                   new Blog("Managed to get a headache toiling over the new cube. Gotta nap.", new Date("08/16/2008")),
                   new Blog("Found a 7x7x7 cube for sale online. Yikes! That one could be a beast.", new Date("08/21/2008")),
                   new Blog("Met up with some fellow cubers to discuss the prospect of a 7x7x7 cube. Mixed feelings.", new Date("08/29/2008")) ];

    //显示所有博客             
    function showBlog (numEntries) {
    	//blog数组排序
    	blog.sort(function(blog1,blog2){ return blog2.date - blog1.date;})

    	if (!numEntries) {
    		numEntries = blog.length;
    	};

    	var i = 0, blogListHTML = "";
    	while(i < blog.length && i < numEntries){
    		blogListHTML += blog[i].toHTML(i%2 == 0);
    		i++;
    	}
    	//设置拼接出来的blog数组字符串
    	document.getElementById("blog").innerHTML = blogListHTML;
    }

    //搜索博客
    function searchBlog () {
    	var searchText = document.getElementById("searchtext").value;
    	for (var i = 0; i < blog.length; i++) {
    		if (blog[i].containsText(searchText)) {
    			alert(blog[i]);
    			break;
    		};
    	};
    	//没有搜索到
    	if (i == blog.length) {
    		alert("Sorry, there are no blog entries containing the search text.");
    	};
    }

    //得到一篇随机博客
    function randomBlog () {
    	var i = Math.floor(Math.random() * blog.length);
    	alert(blog[i]); 
    }
	</script>

</head>
<body onload="showBlog(5);">
	 <h3>YouCube - The Blog for Cube Puzzlers</h3>
    <img src="cube.png" alt="YouCube" />
    <input type="button" id="search" value="Search the Blog" onclick="searchBlog();" />
    <input type="text" id="searchtext" name="searchtext" value="" />
    <div id="blog"></div>
    <input type="button" id="showall" value="Show All Blog Entries" onclick="showBlog();" />
    <input type="button" id="viewrandom" value="View a Random Blog Entry" onclick="randomBlog();" />
</body>
</html>